package controller

import (
	"api/core/errmsg"
	"api/midlib"
	"api/model"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

func LoginBackend(c *gin.Context) {
	var formData model.User
	var code int
	_ = c.ShouldBind(&formData)
	formData,code = model.CheckBackendLogin(formData.Username, formData.Password)
	if code == errmsg.SUCCESS {
		setToken(c, formData)
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code":  code,
			"msg": errmsg.GetErrMsg(code),
			"data": gin.H{
				"name": "",
				"id": 0,
				"token": "",
			},
		})
	}
}

func LoginFrontend(c *gin.Context) {
	var formData model.User
	_ = c.ShouldBindJSON(&formData)
	var code int

	formData, code = model.CheckLoginFront(formData.Username, formData.Password)

	if code == errmsg.SUCCESS {
		setToken(c, formData)
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code":  code,
			"msg": errmsg.GetErrMsg(code),
			"data":  gin.H{
				"name": "",
				"id": 0,
				"token": "",
			},
		})
	}

}



// token生成函数
func setToken(c *gin.Context, user model.User) {
	j := midlib.NewJWT()
	claims := midlib.MyClaims{
		Username: user.Username,
		StandardClaims: jwt.StandardClaims{
			NotBefore: time.Now().Unix() - 100,
			ExpiresAt: time.Now().Unix() + 7200,
			Issuer:    "jgBlog",
		},
	}

	token, err := j.CreateToken(claims)

	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":  errmsg.ERROR,
			"msg": errmsg.GetErrMsg(errmsg.ERROR),
			"data": gin.H{
				"name": "",
				"id": 0,
				"token": "",
			},
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":  errmsg.SUCCESS,
		"msg": errmsg.GetErrMsg(errmsg.SUCCESS),
		"data":    gin.H{
			"name": user.Username,
			"id": user.ID,
			"token": token,
		},
	})
	return
}
